// 导入所需要的包
const mysql = require('mysql')
const env = process.env.NODE_ENV
let mysqlConfig

if (env === 'dev') {
  mysqlConfig = {
    host: '192.168.1.189',
    port: 3307,
    user: 'root',
    password: '123456',
    database: 'test',
    timezone: 'GMT%2B8' // 解决时区时间统一的问题
  }
} else if (env === 'prod') {
  mysqlConfig = {
    host: '192.168.1.189',
    port: 3307,
    user: 'root',
    password: '123456',
    database: 'test',
    timezone: 'GMT%2B8' // 解决时区时间统一的问题
  }
}

// 创建一个连接池
const connPool = mysql.createPool(mysqlConfig)

// 执行一个查询
// conn.query('select * from user_tel', function (error, results, fields) {
//     if (error) throw error;
//     console.log(results);
// });

function query (conn, sql, args = []) {
  return new Promise((resolve, reject) => {
    conn.query(sql, args, function (error, results) {
      if (error) throw reject(error)
      resolve(results)
    })
  })
}
function beginTransaction (conn) {
  return new Promise((resolve, reject) => {
    conn.beginTransaction(function (error) {
      if (error) throw reject(error)
      resolve()
    })
  })
}

function commit (conn) {
  return new Promise((resolve, reject) => {
    conn.commit(function (error) {
      if (error) {
        return conn.rollback(function () {
          reject(error)
        })
      }
      resolve()
    })
  })
}

function rollback (conn) {
  return new Promise((resolve, reject) => {
    conn.rollback(function (error) {
      if (error) throw reject(error)
      resolve()
    })
  })
}

function getConn () {
  return new Promise((resolve, reject) => {
    connPool.getConnection(function (error, conn) {
      if (error) throw reject(error)
      resolve(conn)
    })
  })
}

async function transaction (transactionCallback) {
  let conn
  try {
    // 1. 获取连接
    conn = await getConn()
    // 2. 开启事务
    await beginTransaction(conn)
    // 3. 执行业务单元
    await transactionCallback(conn)
    // 4. 提交
    await commit(conn)

    console.log('commit')
  } catch (error) {
    // 5. 回滚
    if (conn) {
      rollback(conn)
      console.log('roolback', error)
    }
  }
}

module.exports = {
  connPool,
  query,
  beginTransaction,
  commit,
  rollback,
  getConn,
  transaction
}
